﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlServerCe;
using TodoSoft.Data;

namespace Finance.TodoSoft.Data.CompactSql
{
	public class CompactSqlCommandProcessor : SqlCommandProcessorBase
	{
		public CompactSqlCommandProcessor(DbConnection connection)
			: base(connection)
		{
            DbProvider = SqlCeProviderFactory.Instance;
        }
		
        #region ISqlCommandProcessor implementation
		
		protected override IDbDataParameter CreateParameter(IDbCommand sqlCommand, object arg, string name)
		{
			var parameter = sqlCommand.CreateParameter();
			parameter.Value = arg;
			parameter.ParameterName = "@" + name;
			if (arg != null)
				parameter.DbType = GetDbType(arg);
			return parameter;
		}

		private DbType GetDbType(object obj)
		{
			if (obj is Guid)
				return DbType.Guid;
			
			if (obj is Int32)
				return DbType.Int32;
			
			if (obj is String)
				return DbType.String;
			
			if (obj is DateTime)
				return DbType.DateTime;

			if (obj is decimal)
				return DbType.Decimal;

			return DbType.Object;
		}
		
        public override bool IsTableExist(string tableName)
        {
	        var queryResult = ExecuteScalar("select count(*) from INFORMATION_SCHEMA.TABLES where TABLE_NAME=?", tableName);
			return ((int)queryResult) > 0;
        }

		protected override Dictionary<Type, string> CreateDbTypesMap()
	    {
		    return new Dictionary<Type,string> {
			{typeof(Guid),"uniqueidentifier"},
			{typeof(string),"nvarchar"},
			{typeof(int), "integer"},
			{typeof(DateTime), "datetime"},
			{typeof(decimal), "money"}
			};
	    }
		
		#endregion
	}
}
